package com.spring.api.web.controller;

import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.codehaus.jackson.map.util.JSONPObject;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.geetest.sdk.java.GeetestLib;
import com.geetest.sdk.java.web.demo.GeetestConfig;
import com.google.common.collect.Maps;
import com.spera.genutil.IdentifyCodeUtil;
import com.spera.genutil.PasswordEncoder;
import com.spring.api.web.model.ApiUser;
import com.spring.api.web.service.UserApiService;
import com.spring.security.core.annotation.Log;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.core.util.MD5Util;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.model.User;
import com.spring.security.web.service.UserService;

/**
 * 用户信息相关
 * @author wojunyu
 *
 */
@Controller
@RequestMapping(value = "/ssoApi")
public class SsoApiController {
	static Logger logger = Logger.getLogger(SsoApiController.class.getName());
    @Resource
    private UserService userService;

    @Resource
    private JedisCache jedisCache;
    
    @Resource
    private UserApiService userApiService;
    
	@Resource
	private MongoTemplate mongoService;
	
	
	@ResponseBody
    @RequestMapping(value="/getTest", method = RequestMethod.GET)
    public Object getTest(HttpServletRequest request,HttpServletResponse response) throws Exception{
		Map<String,Object> m = Maps.newHashMap();
		m.put("1111", "22222");
		jedisCache.set("aa", "aaa");
		System.out.println(jedisCache.get("aa"));
        return m;
    }
	
    /**
     * 用户登录  by wjy
     * @param token
     * @param userName
     * @param passWord
     * @param callback
     * @return
     */
    @RequestMapping(value = "/login")
    @ResponseBody
    @Log("SsoApiController:function[login]")
    public Object login(String token,String ismobile,String username,String password,
    		String randcode,String deviceCategory,HttpServletRequest request,String callback) {
//    	System.out.println("---------->"+request.getSession().getId());
    	Map<String,Object> m = null;
    	try{
    		m = userApiService.login(token,ismobile,username, password,randcode,deviceCategory,request);
    		if("0".equalsIgnoreCase((String)m.get(ApplicationUtils.STATUS))){
        		String valstatus = IdentifyCodeUtil.checkIdentifyStatus(username, jedisCache);
    	    	m.put("valstatus", valstatus);
        	}
    		
    	}catch(Exception e){
    		e.printStackTrace();
    		m = new HashMap<String,Object>();
    		m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
    	}
    	
        if(ApplicationUtils.isNotNull(callback)){
        	return new JSONPObject(callback, m);
        }else{
        	return m;
        }
    }
    
    /**
     * 
     * @param token
     * @param username
     * @param password
     * @param request
     * @param callback
     * @return
     */
    @RequestMapping(value = "/queryUserDetail")
    @ResponseBody
    public Object queryUserDetail(String token,String callback) throws Exception{
    	Map<String,Object> m = null;
    	try{
    		m = userApiService.queryUserDetail(token);
    	}catch(Exception e){
    		e.printStackTrace();
    		m = new HashMap<String,Object>();
    		m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
    	}
        if(ApplicationUtils.isNotNull(callback)){
        	return new JSONPObject(callback, m);
        }else{
        	return m;
        }
    }
    
    /**
     * 注册提交
     * @param user
     * @param role_id
     * @param file
     * @return
     */
    @RequestMapping(value = "/register")
    @ResponseBody
    public Object register(@Valid User user,String valnum,String deviceCategory,HttpServletRequest request,
            String callback) {
    	Map<String,Object> m = null;
    	try{
    		m = userApiService.register(user,valnum,deviceCategory,request);
    	}catch(Exception e){
    		e.printStackTrace();
    		m = new HashMap<String,Object>();
    		m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
    	}
        if(ApplicationUtils.isNotNull(callback))
        return new JSONPObject(callback, m);
        else  return m;
    }
    

    @RequestMapping(value = "/registerByInviteCode")
    @ResponseBody
    public Object registerByInviteCode(@Valid User user,String valnum,String inviteCode,String deviceCategory,HttpServletRequest request,
             String callback) {
    	Map<String,Object> m = null;
    	try{
    		m = userApiService.registerByInviteCode(user, valnum, inviteCode,deviceCategory,request);
    	}catch(Exception e){
    		e.printStackTrace();
    		m = new HashMap<String,Object>();
    		m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
    	}
        if(ApplicationUtils.isNotNull(callback))
        return new JSONPObject(callback, m);
        else  return m;
    }
    
    
    
    /**
     * 不通过手机号验证注册
     * @param user
     * @param role_id
     * @param file
     * @return
     */
    @RequestMapping(value = "/registerByAssist")
    @ResponseBody
    public Object registerByAssist(User user,String callback,HttpServletRequest request) {
    	Map<String,Object> m = null;
    	try{
    		m = userApiService.registerByAssist(user,request);
    	}catch(Exception e){
    		e.printStackTrace();
    		m = new HashMap<String,Object>();
    		m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
    	}
        if(ApplicationUtils.isNotNull(callback))
        return new JSONPObject(callback, m);
        else  return m;
    }
    
    
    /**
     * 更新用户信息
     * @param token
     * @param user
     * @param callback
     * @return
     */
    @RequestMapping(value = "/saveUserDetail")
    @ResponseBody
    public Object saveUserDetail(String token,ApiUser user,String callback,HttpServletRequest request) {
    	Map<String,Object> m = null;
    	try{
    		m = userApiService.saveUserDetail(token,user,request);
    	}catch(Exception e){
    		e.printStackTrace();
    		m = new HashMap<String,Object>();
    		m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
    	}
        if(ApplicationUtils.isNotNull(callback))
        return new JSONPObject(callback, m);
        else  return m;
    }
    
    /**
     * 登录用户修改密码时发送验证码
     * @param token
     * @param callback
     * @return
     */
    @RequestMapping(value = "/sendPwdToken")
    @ResponseBody
    public Object sendPwdToken(String token,String type,String callback) {
    	Map<String,Object> m = null;
    	try{
    		m = userApiService.sendPwdToken(token,type);
    	}catch(Exception e){
    		e.printStackTrace();
    		m = new HashMap<String,Object>();
    		m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
    	}
        if(ApplicationUtils.isNotNull(callback))
        return new JSONPObject(callback, m);
        else  return m;
    }
    
    /**
     * 用户注册、密码找回时发送的手机验证码
     * @param token
     * @param callback
     * @return
     */
    @RequestMapping(value = "/sendPhoneToken")
    @ResponseBody
    public Object sendPhoneToken(@RequestParam(value="phone") String phone,
    		@RequestParam(value="timestamp") Long timestamp,
    		@RequestParam(value="hashcode") String hashcode,
    		String type,String callback) {
    	Map<String,Object> m = Maps.newHashMap();
    	long defTime = new Date().getTime()/1000-timestamp;
    	if(defTime>120000){
    		m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "请求超时");
    	}else if(jedisCache.exists("sendPhoneToken_"+phone)){
    		m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "验证码已存在，请稍后再发");
    	}else if(!hashcode.equals(MD5Util.string2MD5(PasswordEncoder.translateMobile(phone)+timestamp+"SmsDi6aB0Sp3ra@cZA0GzO6K3y"))){
    		m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "参数有误");
    	}else{
	    	try{
	    		m = userApiService.sendPhoneToken(phone,type);
	    	}catch(Exception e){
	    		e.printStackTrace();
	    		m = new HashMap<String,Object>();
	    		m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "系统异常");
	    	}
    	}
        if(ApplicationUtils.isNotNull(callback))
        return new JSONPObject(callback, m);
        else  return m;
    }
    
    /**
     * 用户密码找回时发送的手机验证码
     * @param token
     * @param callback
     * @return
     */
    @RequestMapping(value = "/findPhoneToken")
    @ResponseBody
    public Object findPhoneToken(@RequestParam(value="phone") String phone,String callback) {
    	Map<String,Object> m = null;
    	try{
    		m = userApiService.findPhoneToken(phone);
    	}catch(Exception e){
    		e.printStackTrace();
    		m = new HashMap<String,Object>();
    		m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
    	}
        if(ApplicationUtils.isNotNull(callback))
        return new JSONPObject(callback, m);
        else  return m;
    }
    
    /**
     * 校验验证码
     */
    @RequestMapping(value = "/checkPhoneToken")
    @ResponseBody
    public Object checkPhoneToken(String phone,String valnum,String type,String callback) {
    	Map<String,Object> m = null;
    	try{
    		m = userApiService.checkPhoneToken(phone,valnum,type);
    	}catch(Exception e){
    		e.printStackTrace();
    		m = new HashMap<String,Object>();
    		m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
    	}
        if(ApplicationUtils.isNotNull(callback))
        return new JSONPObject(callback, m);
        else  return m;
    }
    
    /**
     * 密码修改
     * @param token
     * @param oldpwd
     * @param newpwd
     * @param newpwddb
     * @param callback
     * @return
     */
    @RequestMapping(value = "/changePwd")
    @ResponseBody
    public Object changePwd(String token,
			String pwd_token,
			String pwd_valnum,
			String oldpwd, 
			String newpwd,
			String callback,
			HttpServletRequest request
    		) {
    	Map<String,Object> m = null;
    	try{
    		m = userApiService.changePwd(token,
    			pwd_token,
    			pwd_valnum,
    			oldpwd, 
    			newpwd,
    			request);
    	}catch(Exception e){
    		e.printStackTrace();
    		m = new HashMap<String,Object>();
    		m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
    	}
        if(ApplicationUtils.isNotNull(callback))
        return new JSONPObject(callback, m);
        else  return m;
    }
    
    /**
     * 密码找回
     * @param phone
     * @param newpwd
     * @param newpwddb
     * @param callback
     * @return
     */
    @RequestMapping(value = "/findPwd")
    @ResponseBody
    public Object findPwd(String phone,
    		String val_num,
			String newpwd,
			String deviceCategory,
			String callback) {
    	Map<String,Object> m = null;
    	try{
    		m = userApiService.findPwd(phone,val_num,
    			newpwd,deviceCategory);
    	}catch(Exception e){
    		e.printStackTrace();
    		m = new HashMap<String,Object>();
    		m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
    	}
        if(ApplicationUtils.isNotNull(callback))
        return new JSONPObject(callback, m);
        else  return m;
    }
    
    /**
     * 验证用户名是否已存在
     * @param phone
     * @param callback
     * @return
     */
    @RequestMapping(value = "/checkUser")
    @ResponseBody
    public Object checkUser(String phone,String callback) {
    	Map<String,Object> m = null;
    	try{
    		m = userApiService.checkUser(phone);
    	}catch(Exception e){
    		e.printStackTrace();
    		m = new HashMap<String,Object>();
    		m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
    	}
        if(ApplicationUtils.isNotNull(callback))
        return new JSONPObject(callback, m);
        else  return m;
    }
    
    /**
     * 更新微信积分
     * @param token
     * @param wx_point
     * @param callback
     * @return
     */
    @RequestMapping(value = "/updateWxPoint")
	@ResponseBody
	public Object updateWxPoint(String token, String wx_point, String callback) {
    	Map<String,Object> m = null;
    	try{
    		m = userApiService.updateWxPoint(token,wx_point);
    	}catch(Exception e){
    		e.printStackTrace();
    		m = new HashMap<String,Object>();
    		m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
    	}
        if(ApplicationUtils.isNotNull(callback))
        return new JSONPObject(callback, m);
        else  return m;
    }
    
    
    /**
     * 更新用户头像
     * @param token
     * @param wx_point
     * @param callback
     * @return
     */
    @RequestMapping(value = "/updateUserImageSrc")
	@ResponseBody
	public Object updateUserImageSrc(String token,String c_user_id,@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request,String callback){
    	Map<String,Object> m = null;
    	try{
    		m = userApiService.updateUserImageSrc(token,c_user_id,file,request);
    	}catch(Exception e){
    		e.printStackTrace();
    		m = new HashMap<String,Object>();
    		m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
    	}
        if(ApplicationUtils.isNotNull(callback))
        return new JSONPObject(callback, m);
        else  return m;
    }
    
    
    /**
     * 获取验证码图像
     * @param phone
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/RandCodeImage",method=RequestMethod.GET)
    public void RandCodeImage(String username,HttpServletRequest request,
			 HttpServletResponse response)  throws ServletException,
				IOException{

    	IdentifyingCode idCode = new IdentifyingCode();  
        BufferedImage image =new BufferedImage(idCode.getWidth() , idCode.getHeight() , BufferedImage.TYPE_INT_BGR) ;  
        Graphics2D g = image.createGraphics() ;  
        //定义字体样式  
        Font myFont = new Font("Courier" , Font.ITALIC , 22) ;  
        //设置字体  
        g.setFont(myFont);  
          
        g.setColor(idCode.getRandomColor(200 , 250)) ;  
        //绘制背景  
        g.fillRect(0, 0, idCode.getWidth() , idCode.getHeight()) ;  
          
        g.setColor(idCode.getRandomColor(180, 200)) ;  
        idCode.drawRandomLines(g, 100) ;  
        String valNum = IdentifyCodeUtil.logFail(username, jedisCache);
        logger.info("RandCodeImage----->"+valNum+","+request.getSession().getId());
        if(ApplicationUtils.isNotNull(valNum)){
        	idCode.drawRandomString(valNum, g) ;  
        }
        g.dispose();  
        
        ServletOutputStream sos = response.getOutputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();  
        ImageIO.write(image, "JPEG", bos);  	   
        byte [] buf = bos.toByteArray();  
        sos.write(buf);  
        bos.close();  
        sos.close(); 
    }

	  @RequestMapping(value = "/StartCaptchaServlet",method=RequestMethod.GET)
	  @ResponseBody
	  public Object StartCaptchaServlet(HttpServletRequest request,
				 HttpServletResponse response,String callback) throws IOException {
		  	GeetestLib gtSdk = new GeetestLib(GeetestConfig.getCaptcha_id(), GeetestConfig.getPrivate_key());

			String resStr = "{}";
			
			//自定义userid
			String userid = ApplicationUtils.randomUUID();
			
			//进行验证预处理
			int gtServerStatus = gtSdk.preProcess(userid);
			
			//将服务器状态设置到session中
			request.getSession().setAttribute(gtSdk.gtServerStatusSessionKey, gtServerStatus);
			//将userid设置到session中
			request.getSession().setAttribute("userid", userid);
			resStr = gtSdk.getResponseStr();
			jedisCache.setEx("image_verify_"+userid, 60,userid);

			if(ApplicationUtils.isNotNull(callback))
	        return new JSONPObject(callback, JSON.parse(resStr));
	        else  return JSON.parse(resStr);
	  }
	  
	  
	  @RequestMapping(value = "/sendPhoneVerify",method=RequestMethod.GET)
	  @ResponseBody
	  public Object sendPhoneVerify(@RequestParam(value="phone") String phone,String type,
			  HttpServletRequest request,HttpServletResponse response,String callback) throws IOException {
		  	GeetestLib gtSdk = new GeetestLib(GeetestConfig.getCaptcha_id(), GeetestConfig.getPrivate_key());

		  	String challenge = request.getParameter(GeetestLib.fn_geetest_challenge);
			String validate = request.getParameter(GeetestLib.fn_geetest_validate);
			String seccode = request.getParameter(GeetestLib.fn_geetest_seccode);
				
			//从session中获取gt-server状态
			int gt_server_status_code = (Integer) request.getSession().getAttribute(gtSdk.gtServerStatusSessionKey);
			
			//从session中获取userid
			String userid = (String)request.getSession().getAttribute("userid");
			
			int gtResult = 0;

			if (gt_server_status_code == 1) {
				//gt-server正常，向gt-server进行二次验证
					
				gtResult = gtSdk.enhencedValidateRequest(challenge, validate, seccode, userid);
			} else {
				gtResult = gtSdk.failbackValidateRequest(challenge, validate, seccode);
			}

			Map<String, Object> m = Maps.newHashMap();
			if (gtResult == 1) {
				// 验证成功
				try {
					 m = userApiService.sendPhoneToken(phone,type);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			else {
				// 验证失败
				try {
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "验证失败");
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			if(ApplicationUtils.isNotNull(callback))
	        return new JSONPObject(callback, m);
	        else  return m;
	  }

}

